﻿using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Stores;

namespace OA.Infrastructure.Authentication;

internal class ClientStore : IClientStore
{
    private readonly ICollection<Client> _clients = new List<Client>();

    public ClientStore()
    {
        _clients.Add(new Client()
        {
            ClientId = "ams",
            ClientName = "Assets Management System",
            ClientSecrets = { new Secret("46AA5FCE-40EC-4FA1-9AA0-D556E84AB479".Sha256()) },
            ProtocolType = IdentityServerConstants.ProtocolTypes.OpenIdConnect,
            AccessTokenType = AccessTokenType.Jwt,
            AccessTokenLifetime = 86400,
            AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
            AllowedScopes = new string[] {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.LocalApi.ScopeName,
                "ams_api"
            },
            RequireClientSecret = true,
            UpdateAccessTokenClaimsOnRefresh = true,
            AlwaysIncludeUserClaimsInIdToken = true,
            AllowAccessTokensViaBrowser = true,
            AllowOfflineAccess = true,
        });
    }

    public Task<Client> FindClientByIdAsync(string clientId)
    {
        var client = _clients.FirstOrDefault(x => x.ClientId == clientId) ?? throw new Exception("客户端ID不存在");

        return Task.FromResult(client);
    }
}